package router

import (
	"io/ioutil"
	"net/http"
	"time"

	"github.com/streadway/amqp"
	cedar_session "github.com/tungyao/cedar-session"
)

// 创建群组
// 请在URL上附加account和password
func CreateGroup(w http.ResponseWriter, r *http.Request, s cedar_session.Session) {
	if !CheckAccount(r.URL.Query().Get("account"), r.URL.Query().Get("password")) {
		ToErrorJson(w, "auth account failed")
		return
	}
	group := ImCreateGroup{}
	dt, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		ToErrorJson(w, err.Error())
		return
	}
	group.UnmarshalJSON(dt)
	gid := createRoomId(group.CreateUserId)
	stmt, err := DB.Prepare("insert into `group` set gid=?,name=?,create_user=?,create_user_id=?,status=1,create_time=?")
	if err != nil {
		ToErrorJson(w, err.Error())
		return
	}
	_, err = stmt.Exec(gid, group.Name, group.CreateUser, group.CreateUserId, time.Now().Unix())
	if err != nil {
		ToErrorJson(w, err.Error())
		return
	}
	group.Gid = gid
	out, _ := group.MarshalJSON()
	W(w, out)
}
func JoinGroup(w http.ResponseWriter, r *http.Request, s cedar_session.Session) {
	if !CheckAccount(r.URL.Query().Get("account"), r.URL.Query().Get("password")) {
		ToErrorJson(w, "auth account failed")
		return
	}
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		ToErrorJson(w, err.Error())
		return
	}
	group := ImCreateGroup{}
	group.UnmarshalJSON(data)
	if group.Gid == "" || group.CreateUser == "" || group.CreateUserId == "" {
		ToErrorJson(w, "mission failed : gid or create_user or create_user_id")
		return
	}
	ack, nack := MQ.NotifyConfirm(make(chan uint64, 1), make(chan uint64, 1))
	q, err := MQ.QueueDeclare("im_join_group", true, false, false, false, nil)
	if err != nil {
		ToErrorJson(w, err.Error())
		return
	}

	err = MQ.Publish("", q.Name, false, false, amqp.Publishing{
		ContentType:  "application/json",
		DeliveryMode: amqp.Persistent,
		Body:         data,
	})
	if err != nil {
		ToErrorJson(w, err.Error())
		return
	}
	select {
	case <-ack:
		ToSuccJson(w, "加入群组成功")
	case <-nack:
		ToErrorJson(w, "加入群组失败失败，请稍后重试")
	}
}

// 读出房间id到etcd

// func readGroupToEtcd() {
// 	rows,err:=DB.Query("select gid,name,create_user,create_user_id,create_time from `group` where status=1")
// 	if err!=nil{
// 	    log.Fatalln(err)
// 	}
// 	group:=&ImCreateGroup{}
// 	for rows.Next(){
// 		err:=rows.Scan(&group.Gid,&group.Name,&group.CreateUser,&group.CreateUserId,&group.CreateTime)
// 		if err != nil {
// 			log.Panicln(err)
// 		}
// 		EtcdPut("/group/"+group.Gid,group.CreateUser )
// 	}
// }
